<?php
class SearchMaterialAction extends CAction {
	public function run($query, $start = 0, $limit = 25) {
		$model = Material::model();
		$criteria = new CDbCriteria();
		if (!empty($query)) {
			$criteria->compare($model->getTableAlias() . '.name', $query, true, 'OR');
			$criteria->compare('altNames.name', $query, true, 'OR');
		} elseif ($recents = Yii::app()->recent->get('Material')) {
			$criteria->addInCondition($model->getTableAlias() . '.id', $recents);
		}
		$criteria->order = $model->getTableAlias() . '.name desc';
		$criteria->with = array(
			'altNames',
			'category'
		);
		//		$criteria->join = '';
		$criteria->together = true;
		$criteria->distinct = true;

		$count = $model->count($criteria);

		$criteria->offset = $start;
		$criteria->limit = $limit;

		$materials = $model->findAll($criteria);

		$result = array();
		
		if (!empty($recents)) {
			$unordered=array();
			foreach ($materials as $material) {
				$unordered[$material->id] = array(
								'id' => $material->id,
								'name' => $material->name,
								'category' => $material->category->name,
								'altNames' => implode(', ', $material->altNames)
				);
			}
			foreach ($recents as $recentId){
				if(isset($unordered[$recentId])){
					$result[]=$unordered[$recentId];
				}
			}			
		} else {
			foreach ($materials as $material) {
				$result[] = array(
					'id' => $material->id,
					'name' => $material->name,
					'category' => $material->category->name,
					'altNames' => implode(', ', $material->altNames)
				);
			}
		}
		echo CJSON::encode(
			array(
				'success' => true,
				'data' => $result,
				'total' => $count
			));
	}
}
